package com.ruoyi.controller;

import com.ruoyi.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private StringRedisTemplate redisTemplate;  // RedisTemplate 用于操作 Redis

    // 生成并返回验证码图片
    @GetMapping
    public void generateCaptcha(HttpServletResponse response) throws IOException {
        // 生成验证码字符串
        String captchaCode = CaptchaUtil.generateCode();

        // 使用 CaptchaUtil 生成验证码图片
        BufferedImage captchaImage = CaptchaUtil.generateImage(captchaCode);

        // 将验证码转为小写保存到 Redis，设置过期时间为 5 分钟（可以根据需要调整）
        captchaCode=captchaCode.toLowerCase();
        redisTemplate.opsForValue().set("captcha:" + captchaCode, captchaCode, 5, TimeUnit.MINUTES);

        // 设置响应头，防止浏览器缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 输出图片到响应流
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(captchaImage, "jpeg", out);
        }
    }
}
